#include "contrario.h"

/*

contrario.cpp

*/

void CContrario::OnCollision(CObject *collisionObject){

	if(typeid(*collisionObject)== typeid(CTerrain)){
		position.y = ((CTerrain*)collisionObject)->GetHeight(position.x, position.z) + size/2;

	}
	
	if (collisionObject->tipo == t_JUGADOR){
        velocity *= 0;
    }
    
    if (collisionObject->tipo == t_CONTRARIO){
        if (velocity.x < 0) stepForward(1);
        else stepBack(1);
    }
    
    if (collisionObject->tipo == t_MONTANA){
        stepBack(1);
		direction += 90.0;
    }
    
    if (collisionObject->tipo == t_CHECKPOINT && collisionObject->owner == id){                
        checkpAlcanzado = 1;
        
    }
}



void CContrario::OnPrepare(){
    ProcessAI();
}

void CContrario::Load(){
	// load model
	
    char *skin;
	if (!skinset)
    	skinset = rand()%5;
	
    switch(skinset-1){
        case 0:
         skin="models/coche/viejo.pcx";
         break;
        case 1:
         skin="models/coche/Azul.pcx";
         break;
        case 2:
         skin="models/coche/fuego.pcx";
         break;
        default:
         skin="models/coche/coche.pcx";
     }
    
	CMD2Model::Load("models/coche/tris.md2", skin);
//	LoadCharacter("models/coche/weapon.md2", "models/cochehe/weapon.PCX");
    this->tipo = t_CONTRARIO;
}

void CContrario::loadMap(CTerrain *t){
	map = new RoadMap(t, id); 
	checkpAlcanzado = 1;
}

void CContrario::getAlpha(){
    float disX;         // distancias respecto al checkpoint
	float disZ;
	float hipotenusa;
	
    disX = sigCkp.x-position.x;
    disZ = sigCkp.z-position.z;
    hipotenusa = sqrt(disX*disX + disZ*disZ);
    
    if(disX > 0 && disZ >0){
     alpha=RAD2DEG(asin(disZ/hipotenusa));
            // printf("quad1\n");
    }else if(disX<0 && disZ>0){
     alpha=RAD2DEG(asin((-disX)/hipotenusa)) +90;
            // printf("quad2\n");
    }else if(disX<0 && disZ<0){
     alpha=180.0 + RAD2DEG(asin((-disZ)/hipotenusa));
            // printf("quad3\n");// x:%f - z:%f\n",disX, disZ);
    }else{ 
     alpha=270.0 + RAD2DEG(asin(disX/hipotenusa));
            // printf("quad4\n");
    }
}

void CContrario::OnProcessAI(){
	
    //dar la vuelta si llegas al final!
    if ((position.x > 1700 || position.z > 1700) || (position.x < 0 || position.z < 0))
        direction = fabs(direction - 180);
	
	if (checkpAlcanzado){
		sigCkp = map->nextCheckp(true);
		checkpAlcanzado=0;
	}
    getAlpha();

    if (abs(int(direction-alpha)) > 10){
        direction = alpha;
    }
        
    int boost = rand() % 70;
    velocity = CVector(0.0, 0.0, 70+boost);        
}


